import Koa from 'koa'
import R from 'ramda'
import { resolve } from 'path'
import { sign_err_log } from './controller/errLog.js'
import onerror from 'koa-onerror'

const r = path => resolve(__dirname, path)
const host = process.env.HOST || '127.0.0.1'
const port = process.env.PORT || 3000
const MIDDLEWARES = [ './mongoose/index','./router/router','./websocket/index']
//'./crawler/prolems/terms'
// R.compose(Math.abs, R.add(1), R.multiply(2))(-4)
class Server {
  constructor() {
    this.app = new Koa()
    this.useMiddleWare(this.app)(MIDDLEWARES)
  }
  useMiddleWare(app) {
    return R.map(
            R.compose(//将多个函数合并成一个函数，从右到左执行。
              R.map(i => i(app)),//R.map数组的每个成员依次执行某个函数。
              require,
              i => `${r(i)}`
            )
          )
  }
  async start() {
   
	  this.app.use(async (ctx, next) => {
	    await next()
	    ctx.status = 200 // koa defaults to 404 when it sees that status is unset
	    return new Promise((resolve, reject) => {
	      ctx.res.on('close', resolve)
	      ctx.res.on('finish', resolve)
       
	    })
    })
    onerror(this.app);
    this.app.on('error', (err, ctx) =>{
      // 记录报错信息
      sign_err_log({funcName:err.name,errCont:err.message,status:0,allCont:err})
      console.log('server error监听的服务器报错err字段：', err,'监听的服务器报错err字段结束',);
    });
    
	  this.app.listen(port, host)
	  console.log('Server listening on ' + host + ':' + port) // eslint-disable-line no-console
  }
}

const app = new Server()

app.start()
 // Promise Rejection
process.on('unhandledRejection', err => {
  sign_err_log({funcName:err.name,errCont:err.message,status:0,allCont:err})
  console.log('unhandledRejection监听的服务器报错err字段：', err,'监听的服务器报错err字段结束',);
  // process.nextTick(() => { throw err })
})
// 终极 boss
process.on('uncaughtException', err => {
  sign_err_log({funcName:err.name,errCont:err.message,status:0,allCont:err})
  console.log('uncaughtException监听的服务器报错err字段：', err,'监听的服务器报错err字段结束',);
  // process.nextTick(() => { throw err })
})
